package com.fractal;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import android.widget.ZoomControls;

public class MainActivity extends Activity 
{
	private static final int MENU_SHARE = 1;
    private static final int MENU_ITERATIONS = 2;
    private static final int MENU_COLOR = 3;
    private static final int MENU_RESET = 4;
    private static final int MENU_BOOKMARK = 5;
    private static final int MENU_TOGGLE = 6;
    private static final String SAVEFILENAME = "fractalbookmarks.dat";

	private static final String DEBUG_TAG = "debug";

	private GetDatabase bookmarks;
	private MandelView mandelView;
	private ZoomControls zoomControls;
	private SensorManager sensorManager;
	private Sensor sensor;
	private float randomValue;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.main);

        if(!isOnline())
        {
        	Toast.makeText(this, "No Internet - only loading locally stored markers", Toast.LENGTH_LONG).show();
        }
        
		BufferedInputStream bis = null;
		try 
		{
			bis = new BufferedInputStream (openFileInput(SAVEFILENAME));
			bookmarks = new GetDatabase(bis, getPreferences(Context.MODE_PRIVATE));
		} 
		catch (FileNotFoundException e) { } 
		catch (IOException e) {  }
		finally
		{
			if (bookmarks == null)
				bookmarks = new GetDatabase();
			
			if (bis != null)
			{
				try 
				{
					bis.close();
				} 
				catch (IOException e) { }
			}
		}        

		//bookmarks.update();
        mandelView = (MandelView) findViewById(R.id.surfaceView);
        mandelView.setBookmarks(bookmarks);
        //bookmarks.update();
        zoomControls = (ZoomControls) findViewById(R.id.zoomControls1);
        zoomControls.setOnZoomInClickListener(onZoomInListener);
        zoomControls.setOnZoomOutClickListener(onZoomOutListener);
        
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    }
    
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		FileOutputStream fos = null;
		SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
		try 
		{
			fos = openFileOutput(SAVEFILENAME, Context.MODE_PRIVATE);
			bookmarks.save(fos,prefs);
		} 
		catch (FileNotFoundException e) {  } 
		catch (IOException e) { }
		finally
		{
			if (fos != null)
			{
				try 
				{
					fos.close();
				} 
				catch (IOException e) { }
			}
		}
	}

	@Override
	protected void onStop() 
	{
		super.onPause();
		sensorManager.unregisterListener(sensorListener);
	}

	@Override
	protected void onResume() 
	{
		super.onResume();
		sensorManager.registerListener(sensorListener, sensor, SensorManager.SENSOR_DELAY_NORMAL); 
		
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) 
	{
        super.onCreateOptionsMenu(menu);

        menu.add(0, MENU_COLOR, 0, "Set Colorscheme");
        menu.add(0, MENU_SHARE, 0, "Share");
        menu.add(0, MENU_ITERATIONS, 0, "Set Max Iterations");
        menu.add(0, MENU_BOOKMARK, 0, "Place Marker");
        menu.add(0, MENU_RESET, 0, "Reset");
        menu.add(0, MENU_TOGGLE, 0, "Toggle Markers");

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
    	super.onOptionsItemSelected(item);
        switch (item.getItemId()) 
        {
            case MENU_BOOKMARK:
            	bookmark();
                return true;
            case MENU_SHARE:
            {
            	String path = Images.Media.insertImage(getContentResolver(), mandelView.getImg(), "Fractal", null);
            	Uri uri = Uri.parse(path);
            	final Intent intent = new Intent(Intent.ACTION_SEND);
            	intent.putExtra(Intent.EXTRA_STREAM, uri);
            	intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            	intent.setType("image/bmp");
            	startActivity(Intent.createChooser(intent, "Share"));
            	return true;
            }
            case MENU_COLOR:
            	Intent intent2 = new Intent(this, ColorChooser.class);
            	startActivityForResult(intent2,1);
                return true;
            case MENU_ITERATIONS:
            	showPopup();
                return true;
            case MENU_RESET:
            	mandelView.reset();
                return true;
            case MENU_TOGGLE:
            	if (bookmarks.toggle() == 1)
            		mandelView.render();
            	else
            		mandelView.updateDrag();
                return true;
        }
        return false;
    }
    
    private void showPopup()
    {
    	SetIterations myDialog = new SetIterations(this, "", new OnReadyListener());
        myDialog.show();
    }
    
    private void bookmark()
    {
    	ArrayList<Double> array = mandelView.getInfo();
    	Intent intent = new Intent(this, PutDatabase.class);
    	Double x0 = array.get(0);
    	Double y0 = array.get(1);
    	Double psize = array.get(2);
    	intent.putExtra("x0", String.valueOf(x0));
    	intent.putExtra("y0", String.valueOf(y0));
    	intent.putExtra("psize", String.valueOf(psize));
    	if(isOnline()){
    		startService(intent);
    	}else{
    		Toast.makeText(this, "No Internet - only storing marker locally", Toast.LENGTH_LONG).show();
    	}
        bookmarks.setMark(x0, y0, psize);
        Log.d(DEBUG_TAG,  "Sending info: " + String.valueOf(array.get(0)) + ", " + String.valueOf(array.get(1)) + ", " + String.valueOf(array.get(2)));
        mandelView.render();
    }
    
    private class OnReadyListener implements SetIterations.ReadyListener {
        @Override
        public void ready(String number) {
        	Short i;
        	try
        	{
        		i = Short.valueOf(number);
            	if(i > 10000){
            		Toast.makeText(MainActivity.this, "10000 is max.", Toast.LENGTH_LONG).show();
            		i = 10000;
            	}else if(i < 1){
            		Toast.makeText(MainActivity.this, "Negative ? srsly ?", Toast.LENGTH_LONG).show(); // Dumb text to a dumb user...
            		i = 1;
            	}
        	}catch(NumberFormatException e)
        	{
        		Toast.makeText(MainActivity.this, "10000 is max.", Toast.LENGTH_LONG).show();
        		i = 10000;
        	}
        	
        	mandelView.setMaxIteration(i);
        }
    }
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
    	switch (resultCode)
    	{
    	case 0: // no change
    		break;
    	case Palette.RANDOM:
			mandelView.setPalette(((Math.round(randomValue) % Palette.count()) + 2));
    		break;
    	case Palette.FIRE:
    	case Palette.RAINBOW:
    	case Palette.RAPID:
    	case Palette.BLACKWHITE:
    	case Palette.SKY:
    		mandelView.setPalette(resultCode);
    		break;
    	}
    }

    private final SensorEventListener sensorListener = new SensorEventListener()
    {
		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) { }

		@Override
		public void onSensorChanged(SensorEvent event) 
		{
			randomValue = event.values[0];
		}
    };
    
	private final OnClickListener onZoomInListener = new OnClickListener() 
	{
        public void onClick(View v) {
        	mandelView.zoomIn();
        }
    };
    
    private final OnClickListener onZoomOutListener = new OnClickListener() 
    {
        public void onClick(View v) {
        	mandelView.zoomOut();
        }
    };
    
    public boolean isOnline() 
    {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting())
        {
            return true;
        }
        return false;
    }

}